package com.ftg.learn.util;

import com.mysql.cj.Session;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;
import java.util.Objects;

/**
 * @author kangjx
 * @createTime 2022/7/26
 */
public class MybatisUtil {

    private static SqlSession session = null;

    private static String path = "mybatisconfig.xml";

    /**
     * 初始化session
     */
    static{
        try {
            //i - xml -- java
            Reader reader = Resources.getResourceAsReader(path);

            SqlSessionFactoryBuilder ssfb = new SqlSessionFactoryBuilder();
            SqlSessionFactory ssf = ssfb.build(reader);
            //。。。。
            if(Objects.isNull(session)){
                session = ssf.openSession(true);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获得session
     * @return
     */
    public static SqlSession getSession() {
        return session;
    }
}
